package org.linlinjava.litemall.db.domain;

import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class UserNode {

    private Integer id;

    private String name;

    private Integer pid;

    private List<UserNode> children;


    public static Object buildTree(List<UserNode> userNodes) {
        Set<UserNode> trees = new LinkedHashSet<>();
        Set<UserNode> users = new LinkedHashSet<>();
        List<Integer> ids = userNodes.stream().map(UserNode::getId).collect(Collectors.toList());
        boolean isChild;
        for (UserNode userTreeDTO : userNodes) {
            isChild = false;
            if (userTreeDTO.getPid() == null) {
                trees.add(userTreeDTO);
            }
            for (UserNode it : userNodes) {
                if (userTreeDTO.getId().equals(it.getPid())) {
                    isChild = true;
                    if (userTreeDTO.getChildren() == null) {
                        userTreeDTO.setChildren(new ArrayList<>());
                    }
                    userTreeDTO.getChildren().add(it);
                }
            }

            if (!ids.contains(userTreeDTO.getPid()))
                users.add(userTreeDTO);
        }

        if (CollectionUtils.isEmpty(trees)) {
            trees = users;
        }

        return CollectionUtils.isEmpty(trees) ? userNodes : trees;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public List<UserNode> getChildren() {
        return children;
    }

    public void setChildren(List<UserNode> children) {
        this.children = children;
    }
}
